﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Xml;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Utilities;
using Microsoft.SharePoint.WebControls;
using Kiiro.Common.Entities;
using Kiiro.Common.Utility;
using Kiiro.SiteDefinition.ControlTemplates;
using System.Web.UI.HtmlControls;

namespace Kiiro.SiteDefinition.Core
{
    public partial class AllCustomItems : BasePage
    {
        private BasePage Base
        {
            get { return ( BasePage ) Page; }
        }

        public Pager V2Pager
        {
            get { return (Pager)v2Pager; }
        }

        private Header V2Header
        {
            get { return ( ( MasterPage.KiiroMaster ) Master ).V2Header; }
        }

        public NavigationSub NavigationSub
        {
            get { return KiiroMaster.NavigationSub; }
        }

        public WelcomeMessagePanel V2WelcomeMessagePanel
        {
            get { return (WelcomeMessagePanel)v2WelcomeMessagePanel; }
        }

        private SPList List = null;
        private SPView View = null;
        private SPContentType SPContentType = null;
        private List<string> addedColumns = new List<string> ( ) { "Title" };

        private List<CustomItem> customItems = new List<CustomItem> ( );

        protected void Page_Load ( object sender, EventArgs e )
        {
            litTitle.Text = V2Header.Project.Title;

            V2Pager.NextClick += new EventHandler(RePopulatePage);
            V2Pager.PrevClick += new EventHandler(RePopulatePage);
            V2Pager.EntitiesPerPageChange += new EventHandler(RePopulatePage);

            using (SPWeb web = SPHelpers.GetWeb(Base.SiteCollectionId, Base.ServerRelativeUrl))
            {
                List = web.GetList(Request.Url.ToString());
            } 
            
            if (List != null)
            {
                litTitle.Text += " - " + List.Title;

                View = List.Views["All Items"];

                SPContentType = List.ContentTypes[0];
                
                dataSource.List = List;
                dataSource.SelectCommand = View.SchemaXml;

                AddCommandButtons();
                GenerateColumns();
                FudgeViewXml();
                PopulatePage();
            }
        }

        protected override void OnPreRender(EventArgs e)
        {
            Table headerTable = (Table)genericTable;
            if (genericTable.Rows.Count == 1)
            {
                TableHeaderRow headerRow = (TableHeaderRow) headerTable.Rows[0];

                foreach (TableHeaderCell headerCell in headerRow.Cells)
                {
                    if (headerCell.Controls.Count == 3)
                    {
                        if (V2Pager.SortExpression == headerCell.Controls[1].ID)
                        {
                            //add the sort image at index 2 to be within the span tags
                            if (V2Pager.SortDirection == SortDirection.Ascending || 
                                (string.IsNullOrEmpty(ViewState["OldSortExpression"].ToString()) &&
                                 ViewState["OldSortExpression"].ToString() != headerCell.Controls[1].ID))
                            {
                                headerCell.Controls.AddAt(2,new LiteralControl("<img src='/_layouts/images/Kiiro/icon-sort-asc.gif' />"));
                            }
                            else
                            {
                                headerCell.Controls.AddAt(2, new LiteralControl("<img src='/_layouts/images/Kiiro/icon-sort-desc.gif' />"));
                            }
                        }
                    }
                }
            }

            base.OnPreRender(e);
        }

        #region Page Related Methods

        private void PopulatePage()
        {
            SPQuery query = new SPQuery();
            query.Query = string.Format("<OrderBy><FieldRef Name='{0}' Ascending='{1}'/></OrderBy>", V2Pager.SortExpression, V2Pager.SortDirection == SortDirection.Ascending);
            SPListItemCollection sortedItems = dataSource.List.GetItems(query);

            V2Pager.PopulatePager(sortedItems.Count, Constants.PagerEntity.CustomItems);
            List<SPListItem> customItems = new List<SPListItem>();

            foreach (SPListItem listItem in sortedItems)
            {
                customItems.Add(listItem);
            }

            rptCustomItems.DataSource = customItems.GetRange(V2Pager.PagingIndex, V2Pager.DisplayedCount);
            rptCustomItems.DataBind();

            if (rptCustomItems.Items.Count > 0)
            {
                TableRow trCustom = (TableRow)rptCustomItems.Items[rptCustomItems.Items.Count - 1].FindControl("trCustom");
                trCustom.Attributes.Add("class", "borderless");
            }
            else
            {
                v2Pager.Visible = false;
                pnlPanel.Visible = false;
                v2WelcomeMessagePanel.Visible = true;
                V2WelcomeMessagePanel.ShowPanel = true;
                V2WelcomeMessagePanel.ServerRelativeUrl = this.Base.ServerRelativeUrl;
                V2WelcomeMessagePanel.ShowHidePanel(Constants.PagerEntity.CustomItems, this.Base.PermissionBitsLists);
            }
        }

        private void GenerateColumns ( )
        {
            TableHeaderRow columnsHeader = new TableHeaderRow ( );

            TableHeaderCell title = new TableHeaderCell();
            title.CssClass = "itemsTitle";
            title.Controls.Add(new LiteralControl("<span><p class=\"sort\">"));
            title.Controls.Add(GenerateColumnSortButton("Title", "Title"));
            title.Controls.Add(new LiteralControl("</p></span>"));
            columnsHeader.Cells.Add(title);

            List<string> viewFields = new List<string> ( );
            foreach ( string fieldName in View.ViewFields )
                if (!viewFields.Contains(fieldName) )
                    viewFields.Add ( fieldName );

            int headerWidth = 635;
            if (viewFields.Count > 1)
            {
                if (viewFields.Contains("Title"))
                    headerWidth = 635 / (viewFields.Count - 1);
                else
                    headerWidth = 635 / (viewFields.Count);
            }

            foreach ( string fieldName in viewFields )
            {
                if (!addedColumns.Contains(fieldName) )
                {
                    addedColumns.Add ( fieldName );

                    TableHeaderCell genericColumn = new TableHeaderCell ( );
                    genericColumn.Controls.Add ( new LiteralControl ( "<span><p class=\"sort\">" ) );
                    genericColumn.Controls.Add ( GenerateColumnSortButton ( fieldName, XmlConvert.DecodeName ( fieldName ) ) );
                    genericColumn.Controls.Add ( new LiteralControl ( "</p></span>" ) );
                    genericColumn.CssClass = "items";
                    genericColumn.Attributes.Add("style", "width:" + headerWidth + "px;");
                    columnsHeader.Cells.Add ( genericColumn );
                }
            }

            TableHeaderCell actions = new TableHeaderCell ( );
            actions.Text = "";
            actions.CssClass = "actions";
            columnsHeader.Cells.Add ( actions );

            genericTable.Rows.Add ( columnsHeader );
        }

        private LinkButton GenerateColumnSortButton ( string fieldName, string text )
        {
            LinkButton button = new LinkButton ( );
            button.Text = text;
            button.ID = fieldName;
            button.Command += new CommandEventHandler ( button_Click );
            button.CommandName = fieldName;
            button.CommandArgument = fieldName;

            return button;
        }

        public void button_Click ( object sender, EventArgs e )
        {
            LinkButton link = ( LinkButton ) sender;

            ViewState["OldSortExpression"] = V2Pager.SortExpression;

            V2Pager.SortDirection = SortDirection.Ascending != V2Pager.SortDirection ? SortDirection.Ascending : SortDirection.Descending;
            V2Pager.SortExpression = link.CommandArgument;

            PopulatePage();
        }

        protected void btnDeleteItem_Click ( object sender, EventArgs e )
        {
            LinkButton btnDeleteItem = ( LinkButton ) sender;
            if ( List != null && btnDeleteItem != null )
            {
                int id = int.Parse ( btnDeleteItem.CommandArgument );
                List.Items.DeleteItemById ( id );                
                Response.Redirect ( List.RootFolder.ServerRelativeUrl );
            }
        }

        private void FudgeViewXml ( )
        {
            XmlDocument document = new XmlDocument ( );
            document.LoadXml ( dataSource.SelectCommand );

            SetSortDirection ( document );
            EnsureTitleFieldExists ( document );

            dataSource.SelectCommand = document.OuterXml;
        }

        private void SetSortDirection ( XmlDocument document )
        {
            if ( document.DocumentElement != null )
            {
                XmlNode viewNode = ( XmlNode ) document.DocumentElement;

                XmlNode queryNode = viewNode.SelectSingleNode ( "Query" );
                if ( queryNode == null )
                {
                    queryNode = document.CreateElement ( "Query" );
                    viewNode.AppendChild ( queryNode );
                }

                XmlNode orderByNode = queryNode.SelectSingleNode ( "OrderBy" );
                if ( orderByNode == null )
                {
                    orderByNode = document.CreateElement ( "OrderBy" );
                    queryNode.AppendChild ( orderByNode );
                }

                orderByNode.RemoveAll ( );
                XmlNode fieldRefNode = document.CreateElement ( "FieldRef" );
                orderByNode.AppendChild ( fieldRefNode );

                XmlAttribute attribute = document.CreateAttribute ( "Name" );
                attribute.Value = V2Pager.SortExpression;
                fieldRefNode.Attributes.Append ( attribute );

                attribute = document.CreateAttribute ( "Ascending" );
                attribute.Value = V2Pager.SortDirection != SortDirection.Ascending ? "TRUE" : "FALSE";
                fieldRefNode.Attributes.Append ( attribute );
            }
        }

        private void EnsureTitleFieldExists ( XmlDocument document )
        {
            if ( document.DocumentElement != null )
            {
                XmlNode viewNode = ( XmlNode ) document.DocumentElement;

                XmlNode viewFieldsNode = viewNode.SelectSingleNode ( "ViewFields" );

                XmlNode fieldRefNode = viewFieldsNode.SelectSingleNode ( "FieldRef[@Name='Title']" );
                if ( fieldRefNode == null )
                {
                    fieldRefNode = document.CreateElement ( "FieldRef" );
                    viewFieldsNode.AppendChild ( fieldRefNode );

                    XmlAttribute attribute = document.CreateAttribute ( "Name" );
                    attribute.Value = "Title";
                    fieldRefNode.Attributes.Append ( attribute );
                }
            }
        }

        private void AddCommandButtons ( )
        {
            if ( ContentType != null && Base.PermissionBitsLists [ 0 ] )
            {
                LinkButton command = new LinkButton ( );
                command.Text = "ADD ITEM";// string.Format("ADD {0}", SPContentType.Name.ToUpper());
                command.Attributes.Add ( "class", "icon-add" );
                command.Click += new EventHandler ( btnCreate_Click );
                NavigationSub.Commands.Add ( command );
            }
        }

        public void btnCreate_Click ( object sender, EventArgs e )
        {
            Response.Redirect ( "NewForm.aspx" );
        }

        protected void CustomItems_ItemDataBound ( object source, RepeaterItemEventArgs e )
        {
            SPListItem item = ( SPListItem ) e.Item.DataItem;

            SPWeb web = null;
            SPContext context = null;

            try
            {
                TableRow tr = ( TableRow ) e.Item.FindControl ( "trCustom" );
                web = SPHelpers.GetWeb(SiteCollectionId, ServerRelativeUrl);
                context = SPContext.GetContext ( Context, item.ID, List.ID, web);
                context.FormContext.FormMode = SPControlMode.Display;

                List<string> viewFields = new List<string>();
                foreach ( string fieldName in View.ViewFields )
                    if ( !viewFields.Contains ( fieldName ) )
                        viewFields.Add ( fieldName );

                int cellWidth = 635;
                if (viewFields.Count > 1)
                {
                    if (viewFields.Contains("Title"))
                        cellWidth = 635 / (viewFields.Count - 1);
                    else
                        cellWidth = 635 / (viewFields.Count);
                }

                List<string> addedCells = new List<string> ( ) { "Title" };

                foreach ( string fieldName in viewFields )
                {
                    if ( addedColumns.Contains ( fieldName ) && !addedCells.Contains ( fieldName ) )
                    {
                        addedCells.Add ( fieldName );

                        TableCell x = new TableCell ( );

                        if ( fieldName != "ID" )
                        {
                            BaseFieldControl baseFieldControl = item.Fields.GetFieldByInternalName ( fieldName ).FieldRenderingControl;
                            baseFieldControl.ControlMode = SPControlMode.Display;
                            baseFieldControl.ItemContext = context;
                            baseFieldControl.RenderContext = context;

                            x.Controls.Add ( new LiteralControl ( baseFieldControl.GetDesignTimeHtml() ) );
                        }
                        else if ( fieldName == "ID" )
                        {
                            x.Controls.Add ( new LiteralControl ( item.ID.ToString ( ) ) );
                        }

                        x.CssClass = "items";
                        x.Attributes.Add("style", "width:" + cellWidth + "px;");

                        tr.Cells.AddAt ( tr.Cells.Count - 1, x );
                    }
                }

                HyperLink hypDisplayItem = ( HyperLink ) e.Item.FindControl ( "hypDisplayItem" );
                if ( hypDisplayItem != null )
                {
                    hypDisplayItem.NavigateUrl = string.Format ( "DispForm.aspx?id={0}", item.ID );
                    hypDisplayItem.Text = SPHelpers.ConvertHtmlToKiiroSafeText ( item.Title );
                }

                HyperLink hypEditItem = ( HyperLink ) e.Item.FindControl ( "hypEditItem" );
                if ( hypEditItem != null )
                {
                    hypEditItem.NavigateUrl = string.Format ( "EditForm.aspx?id={0}", item.ID );
                }

                LinkButton btnDeleteItem = ( LinkButton ) e.Item.FindControl ( "btnDeleteItem" );
                if ( btnDeleteItem != null )
                {
                    btnDeleteItem.CommandArgument = item.ID.ToString ( );
                    btnDeleteItem.OnClientClick =
                        string.Format ( "javascript: return confirm('Are you sure you want to delete this {0}?');", SPContentType.Name );
                }

            }
            catch (Exception ex)
            {
                ExceptionManagement.ExceptionManager.HandleException ( ex, false );
            }
            finally
            {
                // commented out because when not we get Failed to Render exception
                //if ( web != null ) web.Dispose ( );
            }

        }

        #endregion
        
        #region Pager Related Methods

        private void RePopulatePage(object sender, EventArgs e)
        {
            PopulatePage();
        }

        #endregion

    }
}

/*************************************************************************
 * 
 * $Log: /Internal Projects/Kiiro/Kiiro.SiteDefinition/12/TEMPLATE/FEATURES/Kiiro.Lists/CustomList/AllCustomItems.aspx.cs $
 * 
 * 19    2/08/10 2:28p Camerons
 * 
 * 18    1/07/10 12:28p Camerons
 * 
 * 17    1/06/10 12:39p Camerons
 * 
 * 16    12/23/09 3:31p Stefanf
 * 
 * 15    10/26/09 9:55a Adamw
 * Case 348
 * 
 * 14    6/10/09 3:58p Shafia
 * commented out the web.Dispose() within CustomItems_ItemDataBound to
 * avoid Failed To Render error
 * 
 * 13    23/09/09 4:34p Shafia
 * implemented the new WelcomeMessagePanel user control on Projects,
 * Users, CustomLists, Work, Documents, and Discussions pages.
 * Links are being displayed based on PermissionsBits[Entity]
 * 
 * 12    18/09/09 2:33p Shafia
 * New Pager Implemented. All data binding is done on the page itself not
 * on the Pager control
 * 
 * 11    9/03/09 4:02p Stefanf
 * 
 * 10    3/09/09 11:07a Camerons
 * Fixed some css issues around columns lining up
 * 
 * 9     2/09/09 4:21p Camerons
 * 
 * 8     9/02/09 9:36a Stefanf
 * 
 * 7     31/08/09 12:20p Shafia
 * 
 * 6     17/08/09 11:07a Camerons
 * Added check-in comments section
 * 
 ************************************************************************/